package com.xiaojie.es.service;

import com.xiaojie.es.entity.User;
import com.xiaojie.es.mapper.UserMapper;
//import com.xiaojie.es.util.ElasticSearchUtils;
import com.xiaojie.es.util.ElasticSearchUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.common.Strings;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.FetchSourceContext;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @Description:
 * @author: yan
 * @date: 2021.11.30
 */
@Service
public class UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private ElasticSearchUtils elasticSearchUtils;
    //添加用户
    public void add() throws IOException {
//        elasticSearchUtils.createIndex("user");
        String chars="11月29日在美国休斯敦进行的2021世界乒乓球锦标赛女子双打决赛中中国组合孙颖莎王曼昱以3比0击败日本组合伊藤美诚早田希娜夺得冠军" +
                "一名德国军官对村民说他们得到了确切的情报村里有游击队并且藏匿着大量枪支和炸药要求村民指认出谁是游击队员并将枪支和炸药供出来这样所有人都可以回去继续睡觉\n" +
                "\n" +
                "事实上村里根本没有游击队员更没有炸德军挨屋搜查只找奇卡洛夫就在那几个知识分子之列作为幸存者之一他在被德军带走后的晚上德军遭到了游击队的袭击趁着混乱他逃了出来回到村里后发现附近村庄的村民在帮忙清理尸体谷仓里的男人全部被烧死或被德国人射杀教堂里面活下来一个女人和三个孩子但都有不同程度的烧伤\n" +
                "\n" +
                "昔日嚣张的德国人面对奇卡洛夫的指控只能承认自己犯下的罪行他们承认犯下罪行的同时却又在推脱罪行扬言一切都是毒品作祟在出发之前所有人都磕了药。当时德军已经出现败相为了提升士气不得不公开分配毒品到一些用于狩猎的老式火枪以及少量炸药那些炸药是修路时留下的已经年代久远发挥不了效用但德国人仍以发现枪支和炸药为借口对村民进行了屠杀";
        String [] arry=new String[]{
                "北京人事经理","天津人事经理","大连人事经理","石家庄人事经理","上海人事经理","武汉人事经理",
                "北京信息经理","天津信息经理","大连信息经理","石家庄信息经理","上海人事经理","武汉信息经理",
                "北京大区董事长","天津大区董事长","大连大区董事长","石家庄大区董事长","上海大区董事长","武汉大区董事长"
        };
        String []address=new String[]{
          "北京东城区","北京西城区","北京海淀区","北京朝阳区","北京丰台区","北京大兴区","北京通州区","北京东直门","北京西直门",
                "天津和平区","天津南开区","天津河西区","天津河东区","天津红桥区","天津北辰区","天津滨海新区","天津东丽区","天津蓟州区",
                "河北石家庄市","沧州市","运河区","桥东区","桥西区","天津北辰区","天津滨海新区","天津东丽区","天津蓟州区",
        };
        ExecutorService executorService = Executors.newFixedThreadPool(10);
        for (int i=0;i<10;i++){
            executorService.execute(()->{
                for (int j=0 ;j<100000;j++){
                    User user=new User();
                    user.setName(RandomStringUtils.random(3,chars));
                    user.setAge(RandomUtils.nextInt(18,40));
                    user.setPosition(arry[RandomUtils.nextInt(0,arry.length)]);
                    user.setAddress(RandomStringUtils.random(20,chars)+address[RandomUtils.nextInt(0,arry.length)]);
                    userMapper.add(user);
                    //添加到es
                    try {
                        elasticSearchUtils.addData(user,"user");
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            });
        }
        executorService.shutdown(); //关闭线程池
    }

    /*
     *
     * @todo 查询用户
     * @author yan
     * @date 2021/11/30 16:24
     * @return java.util.List<java.util.Map<java.lang.String,java.lang.Object>>
     */
    public List<Map<String, Object>> search () throws IOException {
        //构建查询条件
        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
        //精确查询
        //boolQueryBuilder.must(QueryBuilders.wildcardQuery("name", "张三"));
        // 模糊查询
        boolQueryBuilder.filter(QueryBuilders.wildcardQuery("name", "王"));
        // 范围查询 from:相当于闭区间; gt:相当于开区间(>) gte:相当于闭区间 (>=) lt:开区间(<) lte:闭区间 (<=)
        boolQueryBuilder.filter(QueryBuilders.rangeQuery("age").from(18).to(32));
        SearchSourceBuilder query = new SearchSourceBuilder();
        query.query(boolQueryBuilder);
        //需要查询的字段，缺省则查询全部
        String fields = "";
        //需要高亮显示的字段
        String highlightField = "name";
        if (StringUtils.isNotBlank(fields)) {
            //只查询特定字段。如果需要查询所有字段则不设置该项。
            query.fetchSource(new FetchSourceContext(true, fields.split(","), Strings.EMPTY_ARRAY));
        }
        //分页参数，相当于pageNum
        Integer from = 0;
        //分页参数，相当于pageSize
        Integer size = 10;
        //设置分页参数
        query.from(from);
        query.size(size);
        //设置排序字段和排序方式，注意：字段是text类型需要拼接.keyword
        //query.sort("age", SortOrder.DESC);
        query.sort("name" + ".keyword", SortOrder.ASC);
//        return elasticSearchUtils.searchListData("user", query, highlightField);
        return null;
    }
}
